package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.dto.User.UserQueryRequest;
import com.example.demo.entity.Jkpaperorder;
import com.example.demo.entity.User;
import com.example.demo.exception.CustomException;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (user.getName()==null||user.getPassword()==null){
            throw new CustomException("用户信息不能为空");
        }
        boolean register = userService.save(user);
        return register ? Result.success("注册成功") : Result.error("注册失败");
    }
    @PostMapping("/add")
    public Result addUser(@RequestBody User user) {
        if (user.getName()==null||user.getPassword()==null){
            throw new CustomException("用户信息不能为空");

        }
        boolean register = userService.save(user);
        return register ? Result.success("添加成功") : Result.error("添加失败");
    }
    @DeleteMapping("/delete")
    public Result deleteUser(Integer id) {
        if (id<=0)
            throw new CustomException("参数错误");
        return userService.removeById(id) ? Result.success("删除成功") : Result.error("删除失败");

    }
    @PostMapping("/update")
    public Result updateUser(@RequestBody User user) {
        if (user == null){
            throw new CustomException("用户信息不能为空");
        }
        boolean register = userService.updateById(user);
        return register ? Result.success("修改成功") : Result.error("修改失败");
    }
    @GetMapping("/get")
    public Result getUserById(Integer id) {
        if (id<=0)
            throw new CustomException("参数错误");
        User user = userService.getById(id);
        return user != null ? Result.success(user) : Result.error("查询失败");
    }
    @PostMapping("/list/page")
    public Result listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 查询数据库
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return Result.success(userPage);

    }

}
